package com.azunitech.jms.ejb;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import javax.ejb.EJB;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;

import org.apache.log4j.Logger;

import com.google.inject.Injector;
public class AuditInterceptor {
	private static Logger logger = Logger.getLogger(AuditInterceptor.class);
	public AuditInterceptor() {}
	
	@EJB GuiceInjectorHolder injectorHolder;
	
	@AroundInvoke
	public Object audit(InvocationContext ic) throws Exception {
		ic.getContextData().put("caller", "bill");
		 logger.info(ic.getTarget().getClass().getName() + " " + ic.getMethod().getName());
		 logger.info(">>> " + ic.getTarget().getClass().getName() + "-" + ic.getMethod().getName());
		
		 try {

		
		System.out.println("********************Invoking method: " + ic.getMethod() 
					+ " " + ic.getTarget().getClass()
					+ " " + ic.getTarget().getClass().isAnnotationPresent(UsesGuice.class));
	
		Class<?> clz = ic.getTarget().getClass();
		UsesGuice g = clz.getAnnotation(UsesGuice.class);
		System.out.println("********************gggg " + g);
		
		//if (ctx.getTarget().getClass().isAnnotationPresent(UsesGuice.class)) {
			Injector injector = injectorHolder.getInjector();
			System.out.println("********************Inject " + injector);
			injector.injectMembers(ic.getTarget());
			System.out.println("********************Inject ");
		//} 
			 return ic.proceed();
		 } 
		 finally {
			logger.info(ic.getTarget().getClass().getName() + " " + ic.getMethod().getName());
			logger.info("<<< " + ic.getTarget().getClass().getName() + "-" + ic.getMethod().getName());
		 }		
	}

	@PostActivate
	public void postActivate(InvocationContext ic) {
		System.out.println("********************Invoking method: "+ic.getMethod());
	}
  
	@PrePassivate
	public void prePassivate(InvocationContext ic) {
		System.out.println("********************Invoking method: "+ic.getMethod());
	}
}